import json
import os
from datetime import datetime

class Database:
    def __init__(self):
        self.users = []
        self.fields = []
        self.sensors = []
        self.sensor_data = []
        self.tasks = []
        self.roles = []

db = Database()

def save_db_data():
    """保存数据到文件"""
    data = {
        'users': [
            {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'password_hash': user.password_hash,
                'role': user.role,
                'is_active': user.is_active,
                'created_at': user.created_at.isoformat()
            }
            for user in db.users
        ],
        'roles': [
            {
                'id': role.id,
                'name': role.name,
                'permissions': role.permissions,
                'created_at': role.created_at.isoformat()
            }
            for role in db.roles
        ],
        'fields': [
            {
                'id': field.id,
                'name': field.name,
                'area': field.area,
                'boundary': field.boundary,
                'current_crop': field.current_crop,
                'created_at': field.created_at.isoformat()
            }
            for field in db.fields
        ],
        'sensors': [
            {
                'id': sensor.id,
                'name': sensor.name,
                'device_type': sensor.device_type,
                'field_id': sensor.field_id,
                'is_online': sensor.is_online,
                'created_at': sensor.created_at.isoformat()
            }
            for sensor in db.sensors
        ],
        'sensor_data': [
            {
                'id': data.id,
                'sensor_id': data.sensor_id,
                'value': data.value,
                'timestamp': data.timestamp.isoformat()
            }
            for data in db.sensor_data
        ],
        'tasks': [
            {
                'id': task.id,
                'title': task.title,
                'description': task.description,
                'status': task.status,
                'priority': task.priority,
                'field_id': task.field_id,
                'created_at': task.created_at.isoformat(),
                'due_date': task.due_date.isoformat(),
                'completed_at': task.completed_at.isoformat() if task.completed_at else None
            }
            for task in db.tasks
        ]
    }
    
    with open('data.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def load_db_data():
    """从文件加载数据"""
    if not os.path.exists('data.json'):
        print("data.json not found")  # 调试信息
        return
    
    print("Loading data from data.json")  # 调试信息
    with open('data.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    print(f"Loaded data: {data}")  # 调试信息
    
    from .models.user import User
    from .models.field import Field
    from .models.task import Task
    from .models.device import Sensor, SensorData
    from .models.role import Role
    
    # 清空现有数据
    db.users = []
    db.fields = []
    db.tasks = []
    db.sensors = []
    db.sensor_data = []
    db.roles = []
    
    # 初始化角色
    Role.init_roles()
    
    # 加载角色数据
    for role_data in data.get('roles', []):
        role = Role(
            id=role_data['id'],
            name=role_data['name'],
            permissions=role_data['permissions']
        )
        role.created_at = datetime.fromisoformat(role_data['created_at'])
        db.roles.append(role)
    
    # 加载用户数据
    for user_data in data.get('users', []):
        print(f"Creating user: {user_data['username']}")  # 调试信息
        user = User(
            id=user_data['id'],
            username=user_data['username'],
            email=user_data['email'],
            password_hash=user_data['password_hash'],
            role=user_data['role'],
            is_active=user_data['is_active']
        )
        user.created_at = datetime.fromisoformat(user_data['created_at'])
        db.users.append(user)
    
    # 加载农田数据
    for field_data in data.get('fields', []):
        field = Field(
            id=field_data['id'],
            name=field_data['name'],
            area=field_data['area'],        
            boundary=field_data['boundary'],
            current_crop=field_data['current_crop']
        )
        field.created_at = datetime.fromisoformat(field_data['created_at'])
        db.fields.append(field)
    
    # 加载设备数据
    for sensor_data in data.get('sensors', []):
        sensor = Sensor(
            id=sensor_data['id'],
            name=sensor_data['name'],
            device_type=sensor_data['device_type'],
            field_id=sensor_data['field_id'],
            is_online=sensor_data.get('is_online', True)
        )
        sensor.created_at = datetime.fromisoformat(sensor_data['created_at'])
        db.sensors.append(sensor)
    
    # 加载任务数据
    for task_data in data.get('tasks', []):
        task = Task(
            id=task_data['id'],
            title=task_data['title'],
            description=task_data['description'],
            status=task_data['status'],
            priority=task_data['priority'],
            field_id=task_data['field_id'],
            task_type=task_data.get('task_type', 'general'),
            created_by=task_data.get('created_by')
        )
        task.created_at = datetime.fromisoformat(task_data['created_at'])
        if task_data.get('due_date'):
            task.due_date = datetime.fromisoformat(task_data['due_date'])
        if task_data.get('completed_at'):
            task.completed_at = datetime.fromisoformat(task_data['completed_at'])
        db.tasks.append(task)
    
    # ... 加载其他数据 ... 